//
//  HMEditAddressController.m
//  HMMarket
//
//  Created by 孙鹏飞 on 2017/5/16.
//  Copyright © 2017年 homai. All rights reserved.
//

#import "HMEditAddressController.h"
#import "EditAddressTableViewCell.h"
#import "AddressContactCell.h"
#import "DetailedAddressCell.h"
#import "DefaultAddressCell.h"
#import "MGAddress.h"
#import "ChooseLocationView.h"
#import "CitiesDataTool.h"
#import "CheckTool.h"
#import "PositionTool.h"

@interface HMEditAddressController () <UITableViewDelegate,UITableViewDataSource,UITextViewDelegate,NSURLSessionDelegate,UIGestureRecognizerDelegate,DefaultAddressCellDelegate,EditAddressTableViewCellDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic,strong) ChooseLocationView *chooseLocationView;
@property (nonatomic,strong) UIView  *cover;
@property (nonatomic, strong) NSString * dizhilabel;

@property (nonatomic, strong) PositionTool * posi;
@property (nonatomic, strong) NSString * PR;
@property (nonatomic, strong) NSString * CI;
@property (nonatomic, strong) NSString * CO;
@property (nonatomic, strong) NSString * AD;
//@property (nonatomic, assign) BOOL IS_Default;

@end

@implementation HMEditAddressController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.title = @"修改收货地址";
    [self.RightBarItem setTitle:@"保存" forState:UIControlStateNormal];
    [self.RightBarItem addTarget:self action:@selector(rightAction) forControlEvents:UIControlEventTouchUpInside];
    [self setupTableView];
    [self setupAddressList];
    [self setupConfig];
    
    NSLog(@"%@",self.addressMessage.address);
    NSLog(@"%@",self.PR);
}

- (void)setupTableView
{
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([EditAddressTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"edit"];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([AddressContactCell class]) bundle:nil] forCellReuseIdentifier:@"contact"];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([DetailedAddressCell class]) bundle:nil] forCellReuseIdentifier:@"detail"];
//    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([DefaultAddressCell class]) bundle:nil] forCellReuseIdentifier:@"default"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

- (void)setupConfig
{
    self.PR = _addressMessage.province;
    self.CI = _addressMessage.city;
    self.CO = _addressMessage.county;
    self.dizhilabel = [NSString stringWithFormat:@"%@ %@ %@",_addressMessage.province,_addressMessage.city,_addressMessage.county];
//    self.IS_Default = _addressMessage.state;
}

#pragma mark - tableView代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 3) {
        return 100;
    }
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 0) {
        AddressContactCell * cell = [tableView dequeueReusableCellWithIdentifier:@"contact"];
        cell.titleLabel.text = @"收货人";
        cell.inputTextField.text = _addressMessage.consignee;
        return cell;
    } else if (indexPath.section == 0 && indexPath.row == 1) {
        AddressContactCell * cell = [tableView dequeueReusableCellWithIdentifier:@"contact"];
        cell.inputTextField.text = _addressMessage.consignee_tel;
        return cell;
    } else if (indexPath.section == 0 && indexPath.row == 2) {
        EditAddressTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"edit"];
        cell.delegate = self;
        cell.selectedAddressLabel.text = self.dizhilabel;
        return cell;
    } else {
        DetailedAddressCell * cell = [tableView dequeueReusableCellWithIdentifier:@"detail"];
        cell.inputTextView.text = _addressMessage.address;
        cell.placeLabel.hidden = cell.inputTextView.hasText;
        return cell;
    }
    
//    else  {
//        DefaultAddressCell * cell = [tableView dequeueReusableCellWithIdentifier:@"default"];
//        cell.setDefaultBtn.selected = _addressMessage.is_default;
//        cell.delegate = self;
//        return cell;
//    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0 && indexPath.row == 2) {
        [self setAddress];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 5;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 5;
}

/**
 * 添加地址列表
 */
- (void)setupAddressList
{
    [[CitiesDataTool sharedManager] requestGetData];
    [self.view addSubview:self.cover];
}

- (void)setAddress
{
    self.cover.hidden = !self.cover.hidden;
    self.chooseLocationView.hidden = self.cover.hidden;
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    
    CGPoint point = [gestureRecognizer locationInView:gestureRecognizer.view];
    if (CGRectContainsPoint(_chooseLocationView.frame, point)){
        return NO;
    }
    return YES;
}


- (void)tapCover:(UITapGestureRecognizer *)tap{
    
    if (_chooseLocationView.chooseFinish) {
        _chooseLocationView.chooseFinish();
    }
}

- (ChooseLocationView *)chooseLocationView{
    
    if (!_chooseLocationView) {
        _chooseLocationView = [[ChooseLocationView alloc]initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 350, [UIScreen mainScreen].bounds.size.width, 350)];
        
    }
    return _chooseLocationView;
}

- (UIView *)cover{
    
    if (!_cover) {
        _cover = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
        _cover.backgroundColor = [UIColor colorWithWhite:0 alpha:0.2];
        [_cover addSubview:self.chooseLocationView];
        __weak typeof (self) weakSelf = self;
        _chooseLocationView.chooseFinish = ^{
            [UIView animateWithDuration:0.25 animations:^{
                weakSelf.dizhilabel = weakSelf.chooseLocationView.address;
                
                weakSelf.PR = weakSelf.chooseLocationView.address0;
                weakSelf.CI = weakSelf.chooseLocationView.address1;
                weakSelf.CO = weakSelf.chooseLocationView.address2;
                
                weakSelf.view.transform = CGAffineTransformIdentity;
                weakSelf.cover.hidden = YES;
                [weakSelf.tableView reloadData];
            }];
        };
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapCover:)];
        [_cover addGestureRecognizer:tap];
        tap.delegate = self;
        _cover.hidden = YES;
    }
    return _cover;
}

//- (void)DefaultAddressCellDidClickedDefaultBtn:(DefaultAddressCell *)cell
//{
//    self.IS_Default = cell.setDefaultBtn.selected;
//}

- (void)EditAddressTableViewCellDidClickedGetLocationBtn
{
    self.posi = [[PositionTool alloc] init];
    __weak typeof (self) weakSelf = self;
    [self.posi returnLocationMessage:^(NSString *provice, NSString *city, NSString *country,NSString * detailAddress) {
        weakSelf.dizhilabel = [NSString stringWithFormat:@"%@ %@ %@",provice,city,country];
        weakSelf.PR = provice;
        weakSelf.CI = city;
        weakSelf.CO = country;
        weakSelf.addressMessage.address = detailAddress;
        [weakSelf.tableView reloadData];
    }];
}

- (void)rightAction
{
    AddressContactCell * cell0 = (AddressContactCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    
    AddressContactCell * cell1 = (AddressContactCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    
    DetailedAddressCell * cell3 = (DetailedAddressCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]];
    
    NSLog(@"%d",[CheckTool checkMobile:cell1.inputTextField.text]);
    if (cell0.inputTextField.text.length == 0) {
        [HMHUDManager showHUDWithText:@"联系人不能为空"];
        return;
    } else if (cell1.inputTextField.text.length == 0) {
        [HMHUDManager showHUDWithText:@"联系电话不能为空"];
        return;
    } else if (![CheckTool checkMobile:cell1.inputTextField.text]) {
        [HMHUDManager showHUDWithText:@"请输入正确的手机号"];
        return;
    } else if (self.PR == nil || self.PR == NULL) {
        [HMHUDManager showHUDWithText:@"地址不能为空"];
        return;
    } else if (cell3.inputTextView.text.length == 0) {
        [HMHUDManager showHUDWithText:@"详细地址不能为空"];
        return;
    }  else {
        // 1.上传参数
        NSMutableDictionary * param = [NSMutableDictionary dictionary];
        param[@"address_id"] = _addressMessage.address_id;
        param[@"consignee"] = cell0.inputTextField.text;
        param[@"tel"] = cell1.inputTextField.text;
        param[@"province"] = self.PR;
        param[@"city"] = self.CI;
        if (self.CO) {
            param[@"county"] = self.CO;
        } else {
            param[@"county"] = @"";
        }
        param[@"address"] = cell3.inputTextView.text;
//        param[@"state"] = @(self.IS_Default);

        // 2. 发送请求
        [HttpBaseTool post:KUpdateUserAddress params:param success:^(id responseObj) {
            NSLog(@"%@",responseObj[@"msg"]);
            
            if ([responseObj[@"code"] integerValue]== 200) {
                [HMHUDManager showHUDWithText:@"修改地址成功"];
                if (_popBlock) {
                    _popBlock();
                }
                [self.navigationController popViewControllerAnimated:YES];
            } else {
                [HMHUDManager showHUDWithText:@"修改地址失败"];
            }
        } failure:^(NSError *error) {
            if (error.code != NSURLErrorCancelled) { // 并非是取消任务导致的eror，其他错误导致的
                [HMHUDManager showHUDWithText:NetWorkError];
            }
        }];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    NSLog(@"11");
}

@end
